﻿var SPListToolbar = {
    CurrentResources: null,

    init: function () {
        if (SPListToolbar.Resources[_spPageContextInfo.currentLanguage]) {
            SPListToolbar.CurrentResources = SPListToolbar.Resources[_spPageContextInfo.currentLanguage];
        } else {
            SPListToolbar.CurrentResources = SPListToolbar.Resources[SPListToolbar.DefaultLanguage];
        }
    },

    showToolbar: function () {
        var listViewTd = $("#MSOZoneCell_WebPartWPQ2");
        var listViewTable = listViewTd.parents("table").first();
        var html = '<div id="sp-list-toolbar" style="padding: 6px; background: #fcfcfc; border-bottom: #dbddde 1px solid;"></div>';
        listViewTable.before(html);
        var toolbar = $("#sp-list-toolbar");

        var rootFolder = GetUrlKeyValue("RootFolder", true);
        var rootFolderParam = rootFolder ? ("&RootFolder=" + rootFolder) : "";

        // New Item
        var newItemUrl = ctx.editFormUrl.replace('PageType=6', 'PageType=8') + rootFolderParam;
        var newItemOnClick = "NewItem2(event, &quot;" + SPListToolbar.htmlEscape(newItemUrl) + "&quot;);return false;";
        toolbar.append('<a id="sp-list-toolbar-new-item" class="sp-list-toolbar-item" href="' + newItemUrl + '" onclick="' + newItemOnClick +
            '" target="self"><img src="/_layouts/images/newitem.gif" border="0" align="absmiddle" /> ' +
            SPListToolbar.CurrentResources.NewItem + '</a>');

        // New Folder
        var newFolderUrl = newItemUrl + '&Type=1';
        var newFolderOnClick = "NewItem2(event, &quot;" + SPListToolbar.htmlEscape(newFolderUrl) + "&quot;);return false;";
        toolbar.append('<a id="sp-list-toolbar-new-folder" class="sp-list-toolbar-item" href="' + newFolderUrl + '" onclick="' + newFolderOnClick +
            '" target="self" disabled="disabled"><img src="/_layouts/images/nfolder.gif" border="0" align="absmiddle" /> ' +
            SPListToolbar.CurrentResources.NewFolder + '</a>');

        // View
        toolbar.append('<span class="sp-list-toolbar-item"><select id="sp-list-toolbar-view-space" class="ms-RadioText" style="width: 150px;"></select></span>');

        // Search
        var advancedSearchUrl = SPListToolbar.getAdvancedSearchUrl();
        if (advancedSearchUrl) {
            toolbar.append('<a id="sp-list-toolbar-advanced-search" class="sp-list-toolbar-item" href="' + advancedSearchUrl +
                '"><img src="/_layouts/images/spssearch2.gif" border="0" align="absmiddle" /> ' +
                SPListToolbar.CurrentResources.AdvancedSearch + '</a>');
        }

        // List Settings
        toolbar.append('<a id="sp-list-toolbar-list-settings" class="sp-list-toolbar-item" href="../../_layouts/listedit.aspx?List=' + _spPageContextInfo.pageListId +
            '"><img src="/_layouts/images/menulistsettings.gif" style="width: 16px; height: 16px;" border="0" align="absmiddle" /> ' +
            SPListToolbar.CurrentResources.ListSettings + '</a>');

        $(".sp-list-toolbar-item").css("padding", "6px");
    },

    showToolbarDelay: function () {
        var context = SP.ClientContext.get_current();
        var listId = new SP.Guid(_spPageContextInfo.pageListId);
        var list = context.get_web().get_lists().getById(listId);
        var views = list.get_views();
        context.load(list);
        context.load(views);
        context.executeQueryAsync(function () {
            if (list.get_enableFolderCreation()) {
                $("#sp-list-toolbar-new-folder").attr("disabled", "");
            }
            var viewSelectorHtml = '<select id="sp-list-toolbar-view" class="ms-RadioText" style="width: 150px;">';
            var viewEnumerator = views.getEnumerator();
            while (viewEnumerator.moveNext()) {
                var view = viewEnumerator.get_current();
                var viewTitle = view.get_title();
                if (!viewTitle) continue;
                var viewId = view.get_id().toString("B")
                var selected = (ctx.view.toLowerCase() == viewId.toLocaleString());
                var optionHtml = '<option value="' + viewId + (selected ? '" selected="selected' : '') + '">' + SPListToolbar.htmlEscape(viewTitle) + '</option>';
                viewSelectorHtml += optionHtml;
            }
            viewSelectorHtml += '</select>';
            $("#sp-list-toolbar-view-space").after(viewSelectorHtml).hide(); // replace select for IE9
            $("#sp-list-toolbar-view").change(function () {
                $this = $(this);
                var viewEnumerator = views.getEnumerator();
                while (viewEnumerator.moveNext()) {
                    var view = viewEnumerator.get_current();
                    var viewId = view.get_id().toString("B")
                    if (viewId == $this.val()) {
                        var viewParam = GetUrlKeyValue("View", true);
                        if (viewParam) {
                            location.href = view.get_serverRelativeUrl() + location.search.replace(/[vV]iew=\{[a-zA-Z0-9-]+\}/, "View=" + viewId.toUpperCase());
                        } else {
                            location.href = view.get_serverRelativeUrl() + location.search;
                        }
                    }
                }
            });
        }, function () { });
    },

    getAdvancedSearchUrl: function () {
        if (window.g_commandUIHandlers && g_commandUIHandlers.children) {
            for (var i = 0; i < g_commandUIHandlers.children.length; i++) {
                var commandUIHandler = g_commandUIHandlers.children[i];
                if (commandUIHandler.attrs) {
                    if (commandUIHandler.attrs["Command"] == "AdvancedSearch") {
                        return commandUIHandler.attrs["CommandAction"];
                    }
                }
            }
        }
        return null;
    },

    htmlEscape: function (text) {
        return text ? (text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#039;").replace(/</g, "&lt;").replace(/>/g, "&gt;")) : "";
    },

    addEvent: function (eventName, func) {
        if (window.attachEvent) {
            window.attachEvent("on" + eventName, func);
        } else if (window.addEventListener) {
            window.addEventListener(eventName, func, false);
        }
    }
};

var locPath = location.pathname.toLowerCase();
if (locPath.indexOf("/_layouts/") < 0 && locPath.indexOf("/lists/") >= 0 && locPath.indexOf("/dispform.aspx") < 0 && locPath.indexOf("/newform.aspx") < 0 && locPath.indexOf("/editform.axpx") < 0) {
    if (!(window.jQuery)) {
        document.write('<script type="text/javascript" src="../SPListToolbarFiles/jquery-1.4.4.min.js"></' + 'script>');
    }
    document.write('<script type="text/javascript" src="../SPListToolbarFiles/Resources.js"></' + 'script>');
    SPListToolbar.addEvent("load", function () {
        if (!window.ctx || !ctx.view) return;
        SPListToolbar.init();
        SPListToolbar.showToolbar();
        ExecuteOrDelayUntilScriptLoaded(function () {
            SPListToolbar.showToolbarDelay();
        }, "sp.js");
    });
}
